package sdau.hjk.service.Impl;

import com.alibaba.fastjson.JSON;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sdau.hjk.dao.ICovid19DataDao;
import sdau.hjk.entity.Covid19;
import sdau.hjk.service.ICovid19DataService;
import sdau.hjk.util.HttpUtils;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *@version 1.0
 *@author: huangjiakai
 *@create:2021−03-25 15:11
 *@className:sdau.hjk.service.Impl.Covid19DataService
 *@description: TODO
 */
@Service("covid19DataService")
public class Covid19DataService implements ICovid19DataService {
    @Autowired
    private ICovid19DataDao dataDao;

    @Override
    public String updateData() {
        //爬取指定页面
        String html = HttpUtils.getHtml("http://ncov.dxy.cn/ncovh5/view/pneumonia");
        //解析页面中指定内容（id为getAreaStat的标签中的全国疫情数据）
        Document doc = Jsoup.parse(html);
        String text = doc.select("script[id=getAreaStat]").toString();
        String pattern = "\\[(.*)\\]";
        Pattern reg = Pattern.compile(pattern);
        Matcher matcher = reg.matcher(text);
        String jsonStr = "";
        if(matcher.find()){
            jsonStr = matcher.group(0);
        }else{
            System.out.println("no match");
        }
        List<Covid19> pCovidBeans = JSON.parseArray(jsonStr, Covid19.class);//将省份数据解析为json
        if(dataDao.findAll() .size() > 0){
            for(Covid19 pBean : pCovidBeans){
                dataDao.updateData(pBean);
            }
        }else{
            for (Covid19 pBean : pCovidBeans){
                dataDao.saveData(pBean);
            }
        }
        return "更新完成";
    }

    @Override
    public List<Covid19> findAll() {
        return dataDao.findAll();
    }
}
